package Communication;


import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import Controller.SystemController;


/**
 * MySqlConnection is the class for MySql DataBase Loading
 */
public class MySqlConnection implements Serializable {
	private static final long serialVersionUID = 42L;

	private Connection conn = null;
	private String userName = null;
	private String password = null;
	private String host=null;
	

/**
 * Make Connection to the database in mysql
 */
	public void connect() {
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (Exception ex) {
			 
		}

		try {
				System.out.println("Connecting to database...");
				conn = DriverManager.getConnection("jdbc:mysql://"+host+"/ccrm", userName, password);
			    System.out.println("SQL connection succeed");
			    SystemController.displayMessage("SQL connection succeed");

		} catch (SQLException ex) {
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
			
		}
	}

/**
 *  Gets values from database through ResultSet using specific query
 * @param rs
 * @param query
 * @return
 */
	public ResultSet getFromDB(ResultSet rs, String query) {
		try {
			PreparedStatement stmt = conn.prepareStatement(query);
			rs = stmt.executeQuery(query);
			return rs;
			
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 *  Updates the database using specific query
	 * @param query
	 */
	public void updateDB(String query) {
		try {
			Statement stmt = conn.prepareStatement(query);
			stmt.executeUpdate(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * get the password
	 * @return password
	 */
	public String getPassword() {
		return password;
	}
	/**
	 * get the user name
	 * @return userName
	 */
	public String getUserName() {
		return userName;
	}
	/**
	 *  set Password
	 * @param password
	 */
	public void setPassword(String password) {
		this.password = password;
	}
	/**
	 * set the user name
	 * @param userName
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	public void setHost(String host)
	{
		this.host=host;
	}
}

	